package com.wenjie.utils;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

public class IpUtils {

    public static final String appcode = "9bbbcb366c964bd2bef4728e04b4c70e";

    /**
     * @Description 根据ip查询实际地址信息
     * @author wenjie
     * @date 2024/8/26 16:50
     */
    public static String getBeautifyAddrByIp(String ip) {
        JSONObject dataObject = getAddrByIp(ip);
        if (dataObject == null) return null;
        String region = dataObject.getStr("region");// 省
        String city = dataObject.getStr("city");// 市
        String district = dataObject.getStr("district");// 区
        return region + "-" + city + "-" + district;
    }

    /**
     * @Description 根据ip 查询实际地址信息
     * @author wenjie
     * @date 2024/8/26 16:50
     */
    public static JSONObject getAddrByIp(String ip) {

        //  127.0.0.1 经不要查询了 浪费请求次数
        if ("127.0.0.1".equals(ip.trim())) {
            JSONObject jsonObject = JSONUtil.parseObj("{\n" + "    \"ip\": \"127.0.0.1\",\n" + "    \"long_ip\": \"xxxxx\",\n" + "    \"isp\": \"xxxxx\",\n" + "    \"area\": \"xxxxx\",\n" + "    \"region_id\": \"xxxxx\",\n" + "    \"region\": \"本地\",\n" + "    \"city_id\": \"xxxxx\",\n" + "    \"city\": \"本地\",\n" + "    \"district\": \"本地\",\n" + "    \"district_id\": \"xxxxx\",\n" + "    \"country_id\": \"xxxxx\",\n" + "    \"country\": \"xxxxx\",\n" + "    \"lat\": \"本地\",\n" + "    \"lng\": \"本地\"\n" + "  }");
            return jsonObject;
        }


        String host = "https://c2ba.api.huachen.cn";
        String path = "/ip";
        String method = "GET";
        Map<String, String> headers = new HashMap();
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap();
        querys.put("ip", ip);

        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            System.out.println(EntityUtils.toString(response.getEntity()));

            JSONObject jsonObject = JSONUtil.parseObj(response.getEntity());
            if (!jsonObject.getInt("res").equals(200)) return null;
            JSONObject dataObject = jsonObject.getJSONObject("data");
            return dataObject;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
